package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.model.ProductSku;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductDetailsMapper productDetailsMapper;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public List<Product> selectProductList() {
        return baseMapper.selectProductList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveProduct(Product product) {
        //1.新增商品SPU信息
        //1.1 设置商品初始状态：0：未上架
        product.setStatus(0);
        //1.2 设置商品创建人
        product.setCreateBy(SecurityUtils.getUsername());
        //1.3 保存商品SPU信息
        baseMapper.insert(product);
        //1.4 获取商品ID
        Long productId = product.getId();

        //2.新增商品详情信息
        //2.1 构建商品详情对象
        ProductDetails productDetails = new ProductDetails();
        //2.2 获取商品对象详情图片列表，处理图片为图片列表赋值
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if (!CollectionUtils.isEmpty(detailsImageUrlList)) {
            String imageUrl = String.join(",", detailsImageUrlList);
            productDetails.setImageUrls(imageUrl);
        }
        //2.3 关联商品ID
        productDetails.setProductId(productId);
        //2.4 保存商品详情信息
        productDetails.setCreateBy(SecurityUtils.getUsername());
        productDetailsMapper.insert(productDetails);

        //3.批量新增商品SKU信息 同时 批量新增商品库存信息
        //3.1 获取商品SKU列表
        List<ProductSku> skuList = product.getProductSkuList();
        if (!CollectionUtils.isEmpty(skuList)) {
            int num = 1;
            for (ProductSku sku : skuList) {
                //3.2 保存SKU信息
                //3.2.1 生成商品sku编号 规则：商品ID_1
                sku.setSkuCode(productId + "_" + num++);
                //3.2.2 生产商品sku名称 规则：商品名称+规格参数
                sku.setSkuName(product.getName() + " " + sku.getSkuSpec());
                //3.2.3 关联商品SPUID
                sku.setProductId(productId);
                //3.2.4 设置初始状态
                sku.setStatus(0);
                //3.2.5 设置创建人
                sku.setCreateBy(SecurityUtils.getUsername());
                //3.2.6 保存SKU信息
                productSkuMapper.insert(sku);
                //3.2.7 获取SKUID
                Long skuId = sku.getId();

                //3.3 保存SKU库存
                SkuStock skuStock = new SkuStock();
                skuStock.setSkuId(skuId);
                skuStock.setStatus(0);
                skuStock.setTotalNum(sku.getStockNum());
                skuStock.setAvailableNum(sku.getStockNum());
                skuStock.setLockNum(0);
                skuStock.setSaleNum(0);
                skuStock.setCreateBy(SecurityUtils.getUsername());
                skuStockMapper.insert(skuStock);
            }
        }
    }
@Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Long spuId, Integer status) {
    //1.修改商品SPU状态
    Product product = new Product();
    product.setId(spuId);
    product.setStatus(status);
    product.setUpdateBy(SecurityUtils.getUsername());
    baseMapper.updateById(product);

    //2.修改商品SKU状态
    ProductSku productSku = new ProductSku();
    productSku.setStatus(status);
    productSku.setUpdateBy(SecurityUtils.getUsername());
    productSkuMapper.update(productSku, new LambdaUpdateWrapper<ProductSku>()
            .eq(ProductSku::getProductId, spuId));

//    LambdaUpdateWrapper<ProductSku> updateWrapper = new LambdaUpdateWrapper<>();
//    updateWrapper.set(ProductSku::getStatus, status);
//    updateWrapper.eq(ProductSku::getProductId, spuId);
//    productSkuMapper.update(null, updateWrapper);


    //3.修改商品库存状态
    //3.1 查询商品SKUID列表
    LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper
            .eq(ProductSku::getProductId, spuId)
            .select(ProductSku::getId);
    List<Long> skuIdList = productSkuMapper
            .selectList(queryWrapper)
            .stream().map(ProductSku::getId)
            .collect(Collectors.toList());

    //3.2 更新商品SKU库存状态
    LambdaUpdateWrapper<SkuStock> stockLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
    stockLambdaUpdateWrapper.set(SkuStock::getStatus, status);
    stockLambdaUpdateWrapper.in(SkuStock::getSkuId, skuIdList);
    skuStockMapper.update(null, stockLambdaUpdateWrapper);

    //4.判断上下架状态，如果是上架：将商品加入到bitmap中，如果下架：从bitmap中删除
    skuIdList.forEach(skuId -> {
        if (status == 1) {
            redisTemplate.opsForValue().setBit("product:sku:data", skuId, true);
        } else if (status == -1) {
            redisTemplate.opsForValue().setBit("product:sku:data", skuId, false);
        }
    });
    }
@Transactional(rollbackFor = Exception.class)
    @Override
    public void removeProduct(List<Long> ids) {
    baseMapper.deleteBatchIds(ids);

    //2.根据商品SPUID查询SKUID列表
    List<ProductSku> productSkuList = productSkuMapper.selectList(
            new LambdaQueryWrapper<ProductSku>()
                    .in(ProductSku::getProductId, ids)
                    .select(ProductSku::getId)
    );
    if (!CollectionUtils.isEmpty(productSkuList)) {
        List<Long> skuIdList = productSkuList
                .stream()
                .map(ProductSku::getId)
                .collect(Collectors.toList());
        //3.删除商品SKU表
        productSkuMapper.deleteBatchIds(skuIdList);
        //4.删除商品SKU库存表
        skuStockMapper.delete(
                new LambdaQueryWrapper<SkuStock>()
                        .in(SkuStock::getSkuId, skuIdList)
        );
    }
    //5.删除商品SPU详情表
    productDetailsMapper.delete(
            new LambdaQueryWrapper<ProductDetails>()
                    .in(ProductDetails::getProductId, ids)
    );
    }
}
